package com.murong.ai.chat.controller;

import com.murong.ai.chat.domain.FlowCallService;
import com.murong.ai.chat.domain.chatbot.ChatBotService;
import com.murong.ai.chat.domain.speech2text.STTService;
import com.murong.ai.chat.domain.text2speech.TTSService;
import com.murong.ai.chat.infrastructure.utils.MrSpringContextHolder;
import com.murong.ai.chat.infrastructure.utils.PrintUtils;
import lombok.SneakyThrows;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.Resource;
import org.springframework.core.io.ResourceLoader;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.sound.sampled.*;
import java.io.File;

@RestController
@RequestMapping("/api/flow")
public class FlowController {
    @Autowired
    ResourceLoader resourceLoader;
    @Autowired
    TTSService ttsService;
    @Autowired
    STTService sttService;
    @Autowired
    ChatBotService chatBotService;
    @Autowired
    private TargetDataLine microphone;
    @Autowired
    private AudioFormat audioFormat;

    @RequestMapping("/start")
    public void start(){

        //初始化
        sayIamHere();

        //检测用户语音转换成文字
        String content = sttService.execute();
        PrintUtils.logLine("request text: " + content);

        //调用聊天机器人
        String response = null;
        if(content!=null && !content.isEmpty()){
            PrintUtils.logLine("communicating with chatbot...");
            response=chatBotService.call(content);
        }
        PrintUtils.logLine("response text: " + response);

        //文字转换成语音
        if(response!=null){
            try {
                ttsService.execute(response);
            }catch (Exception e){
                System.err.println(e.getMessage());
            }
        }
    }

    @SneakyThrows
    public void sayIamHere(){
        Resource resource =MrSpringContextHolder
                .getBean(ResourceLoader.class).getResource("classpath:audio_files/i'mHere.wav");
        AudioInputStream audioInputStream = AudioSystem.getAudioInputStream(resource.getFile());
        Clip clip = AudioSystem.getClip();
        clip.open(audioInputStream);
        clip.start();
        Thread.sleep(1000);
        PrintUtils.logLine("I'm here...");
        clip.close();
        microphone.open(audioFormat);
        microphone.start();
    }
}
